iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 22
0
自我挑戰組

資料結構大便當系列 第 22

[Day 22] Binary Search Tree IIII

  • 分享至 

  • xImage
  •  

Binary Search Tree (BST) Operations cheatsheet

根據昨天的簡單 leetcode 練習
今天走一點學術風格
把幾個 operations 整理一下。

Search by recursive

TREE-SEARCH(x, k)
    if x == NIL or k == x.key
        return x
    if k < x.key
        return TREE-SEARCH(x.left, k)
    else return TREE-SEARCH(x. right, k)

https://ithelp.ithome.com.tw/upload/images/20191004/20120250ltZOy26HBn.png

Search by iterative

ITERATIVE-TREE-SEARCH(x, k)
    while x != NIL and k != x.key
        if k < x.key
            x = x.left
        else
            x = x.right
    return x

不管是哪種方法,只要記得 BST 的基本特性(左小右大),都可以很直覺的想出上面的 code

Tree Minimum / Maxmum

TREE-MINIMUM(x)
    while x.left != NIL
        x = x.left
    return x
TREE-MAXMUM(x)
    while x.right != NIL
        x = x.right
    return x

Find the Next Larger Element

TREE-SUCCESSOR(x)
    if x.left != NIL
        return TREE-MINIMUM(x.right)
    y = x.p
    while y != NIL and x == y.right
        x = y
        y = y.p
    return y

Insertion

TREE-INSERT(T, z)
    y = NIL
    x = T.root
    while x != NIL
        y = x
        if z.key < x.key
            x = x.left
        else
            x = x.right
    z.p = y
    if y == NIL
        T.root = z
    else if z.key < y.key
        y.left = z
    else
        y.right = z

https://ithelp.ithome.com.tw/upload/images/20191004/20120250NNfrT6e5jk.png

Transplant Routine

當點被移除時,將其他的點轉移上來。看圖:
https://ithelp.ithome.com.tw/upload/images/20191004/201202503sj3QEvino.png
https://ithelp.ithome.com.tw/upload/images/20191004/20120250BSlB2X05Pw.png

TRANSPLANT(T, u, v)
    if u.p == NIL
        T.root = v
    else if u == u.p.left
        u.p.left = v
    else
        u.p.right = v
    if v != NIL
        v.p = u.p

Delete a key/Node

TREE-DELETE(T, z)
    if z.left == NIL
        TRANSPLANT(T, z, z.right)
    else if z.right == NIL
        TRANSPLANT(T, z, z.left)
    else
        y = TREE-MINIMUM(z.right)
        if y.p != z
            TRANSPLANT(T, y, y.right)
            y.right = z.right
            y.right.p = y
        TRANSPLANT(T, z, y)
        y.left = z.left
        y.left.p = y

上一篇
[Day 21] Binary Search Tree III
下一篇
[Day 23] Red–Black Tree I
系列文
資料結構大便當30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言